﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TA.DotNetUtils;
using TA.JSON;
using System.ComponentModel;

namespace TA.Turbo.Controls
{
	public class TreeNodeCollection : VList<BaseTreeNode>, IJsonCompatible
	{
		#region PUBLIC
		#region METHODS
		public BaseTreeNode FindById(string uniqueId)
		{
			foreach (BaseTreeNode node in this)
			{
				if (string.Equals(node.UniqueId, uniqueId)) return node;

				BaseTreeNode t = node.Children.FindById(uniqueId);
				if (t != null)
					return t;
			}
			return null;
		}
		#endregion
		#endregion
		#region INTERNAL
		#region VARS
		#endregion
		#region PROPS
		#endregion
		#region METHODS
		#region JSON
		/// <summary>
		/// Gets true if there are any items.
		/// </summary>
		[Browsable(false)]
		public bool IsDirty
		{
			get { return this.Count > 0; }
		}
		/// <summary>
		/// Serializes this collection by outputting an array.
		/// </summary>
		/// <param name="jw"></param>
		public void Serialize(JsonWriter jw)
		{
			this.SerializeArray(jw);
		}
		/// <summary>
		/// SerializeContents.
		/// </summary>
		/// <param name="jw"></param>
		public void SerializeContents(JsonWriter jw)
		{
			foreach (BaseTreeNode i in this)
				i.Serialize(jw);
		}
		/// <summary>
		/// Deserializes this collection by reading an array.
		/// </summary>
		/// <param name="jr"></param>
		public void Deserialize(IJsonReader jr)
		{
			this.DeserializeArray(jr);
		}
		/// <summary>
		/// DeserializeContent.
		/// </summary>
		/// <param name="jr"></param>
		/// <param name="propShortName"></param>
		public void DeserializeContent(IJsonReader jr, string propShortName)
		{
			BaseTreeNode node = null;
			jr.DeserializeObject(delegate(string propName, IJsonReader j)
			{
				if (propName.Equals("Y"))
				{
					TreeNodeType type = (TreeNodeType)(long)jr.Value;
					switch (type)
					{
						case TreeNodeType.CheckBox: node = new CheckBoxNode(); break;
						case TreeNodeType.Expansion: node = new ExpansionNode(); break;
						case TreeNodeType.HyperLink: node = new HyperLinkNode(); break;
						case TreeNodeType.Selection: node = new SelectionNode(); break;
						case TreeNodeType.Template: node = new TemplateNode(); break;
					}
				}
				if (node != null)
				{
					node.DeserializeContent(j, propName);
				}
			});

			this.Add(node);
		}
		#endregion
		#endregion
		#endregion
	}
}
